package com.shanghaionstar.nav.util;

import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.nav.model.LocateStatus;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by OnStar on 2017/2/14.
 */

public class FindMyLocate {

    private AbstractMapActivity mapActivity;
    private NavHolder  navHolder;
    private Subscription locateSubscription;
    private MapHandler mapHandler;

    public FindMyLocate(AbstractMapActivity mapActivity , MapHandler mapHandler) {
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
    }

    public void beginLocate() {
        registMyLocate();
        NavHolder.getInstance(mapActivity.getApplicationContext()).findMyLocation();
    }

    /**
     * 注册广播以接受位置变更
     */
    private void registMyLocate() {
        locateSubscription = RxBus.getDefault().toObserverable(RxConstants.LOCATE, LocateStatus.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<LocateStatus>() {
                    @Override
                    public void call(LocateStatus locateStatus) {
                        requestMyLocate();
                    }
                });
    }


    /**
     * 主动请求位置变化信息
     */
    private void requestMyLocate() {
        navHolder = NavHolder.getInstance(mapActivity);
//        LocateStatus locateStatus = LocateStatus.LOCATED;
        /**
         * 一直报 enum的ordinal（）方法错误
         */
        LocateStatus locateStatus = navHolder.getLocateStatus();
        switch (locateStatus) {
            case LOCATING:
                break;
            case LOCATED:
                if (navHolder.getMyLocation() != null) {
                    mapHandler.geoCoderGps(navHolder.getMyLocation().getLatitude(), navHolder.getMyLocation().getLongitude(), LocationType.MYSELF);
                }
                break;
            case LOCATE_FAIL:
                break;
        }
    }

    public void clear() {
        if(locateSubscription != null  && locateSubscription.isUnsubscribed()) {
            locateSubscription.unsubscribe();
            locateSubscription = null;
        }
    }
}
